/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controladores;

import controladores.exceptions.IllegalOrphanException;
import controladores.exceptions.NonexistentEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entity.ObjetoEntity;
import entity.TipoEntity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Gaston
 */
public class TipoEntityJpaController implements Serializable
{

    public TipoEntityJpaController(EntityManagerFactory emf)
    {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(TipoEntity tipoEntity)
    {
        if (tipoEntity.getObjetoEntityCollection() == null)
        {
            tipoEntity.setObjetoEntityCollection(new ArrayList<ObjetoEntity>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<ObjetoEntity> attachedObjetoEntityCollection = new ArrayList<ObjetoEntity>();
            for (ObjetoEntity objetoEntityCollectionObjetoEntityToAttach : tipoEntity.getObjetoEntityCollection())
            {
                objetoEntityCollectionObjetoEntityToAttach = em.getReference(objetoEntityCollectionObjetoEntityToAttach.getClass(), objetoEntityCollectionObjetoEntityToAttach.getId());
                attachedObjetoEntityCollection.add(objetoEntityCollectionObjetoEntityToAttach);
            }
            tipoEntity.setObjetoEntityCollection(attachedObjetoEntityCollection);
            em.persist(tipoEntity);
            for (ObjetoEntity objetoEntityCollectionObjetoEntity : tipoEntity.getObjetoEntityCollection())
            {
                TipoEntity oldTipoOfObjetoEntityCollectionObjetoEntity = objetoEntityCollectionObjetoEntity.getTipo();
                objetoEntityCollectionObjetoEntity.setTipo(tipoEntity);
                objetoEntityCollectionObjetoEntity = em.merge(objetoEntityCollectionObjetoEntity);
                if (oldTipoOfObjetoEntityCollectionObjetoEntity != null)
                {
                    oldTipoOfObjetoEntityCollectionObjetoEntity.getObjetoEntityCollection().remove(objetoEntityCollectionObjetoEntity);
                    oldTipoOfObjetoEntityCollectionObjetoEntity = em.merge(oldTipoOfObjetoEntityCollectionObjetoEntity);
                }
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(TipoEntity tipoEntity) throws IllegalOrphanException, NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            TipoEntity persistentTipoEntity = em.find(TipoEntity.class, tipoEntity.getId());
            Collection<ObjetoEntity> objetoEntityCollectionOld = persistentTipoEntity.getObjetoEntityCollection();
            Collection<ObjetoEntity> objetoEntityCollectionNew = tipoEntity.getObjetoEntityCollection();
            List<String> illegalOrphanMessages = null;
            for (ObjetoEntity objetoEntityCollectionOldObjetoEntity : objetoEntityCollectionOld)
            {
                if (!objetoEntityCollectionNew.contains(objetoEntityCollectionOldObjetoEntity))
                {
                    if (illegalOrphanMessages == null)
                    {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain ObjetoEntity " + objetoEntityCollectionOldObjetoEntity + " since its tipo field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<ObjetoEntity> attachedObjetoEntityCollectionNew = new ArrayList<ObjetoEntity>();
            for (ObjetoEntity objetoEntityCollectionNewObjetoEntityToAttach : objetoEntityCollectionNew)
            {
                objetoEntityCollectionNewObjetoEntityToAttach = em.getReference(objetoEntityCollectionNewObjetoEntityToAttach.getClass(), objetoEntityCollectionNewObjetoEntityToAttach.getId());
                attachedObjetoEntityCollectionNew.add(objetoEntityCollectionNewObjetoEntityToAttach);
            }
            objetoEntityCollectionNew = attachedObjetoEntityCollectionNew;
            tipoEntity.setObjetoEntityCollection(objetoEntityCollectionNew);
            tipoEntity = em.merge(tipoEntity);
            for (ObjetoEntity objetoEntityCollectionNewObjetoEntity : objetoEntityCollectionNew)
            {
                if (!objetoEntityCollectionOld.contains(objetoEntityCollectionNewObjetoEntity))
                {
                    TipoEntity oldTipoOfObjetoEntityCollectionNewObjetoEntity = objetoEntityCollectionNewObjetoEntity.getTipo();
                    objetoEntityCollectionNewObjetoEntity.setTipo(tipoEntity);
                    objetoEntityCollectionNewObjetoEntity = em.merge(objetoEntityCollectionNewObjetoEntity);
                    if (oldTipoOfObjetoEntityCollectionNewObjetoEntity != null && !oldTipoOfObjetoEntityCollectionNewObjetoEntity.equals(tipoEntity))
                    {
                        oldTipoOfObjetoEntityCollectionNewObjetoEntity.getObjetoEntityCollection().remove(objetoEntityCollectionNewObjetoEntity);
                        oldTipoOfObjetoEntityCollectionNewObjetoEntity = em.merge(oldTipoOfObjetoEntityCollectionNewObjetoEntity);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = tipoEntity.getId();
                if (findTipoEntity(id) == null)
                {
                    throw new NonexistentEntityException("The tipoEntity with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            TipoEntity tipoEntity;
            try
            {
                tipoEntity = em.getReference(TipoEntity.class, id);
                tipoEntity.getId();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The tipoEntity with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<ObjetoEntity> objetoEntityCollectionOrphanCheck = tipoEntity.getObjetoEntityCollection();
            for (ObjetoEntity objetoEntityCollectionOrphanCheckObjetoEntity : objetoEntityCollectionOrphanCheck)
            {
                if (illegalOrphanMessages == null)
                {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This TipoEntity (" + tipoEntity + ") cannot be destroyed since the ObjetoEntity " + objetoEntityCollectionOrphanCheckObjetoEntity + " in its objetoEntityCollection field has a non-nullable tipo field.");
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(tipoEntity);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<TipoEntity> findTipoEntityEntities()
    {
        return findTipoEntityEntities(true, -1, -1);
    }

    public List<TipoEntity> findTipoEntityEntities(int maxResults, int firstResult)
    {
        return findTipoEntityEntities(false, maxResults, firstResult);
    }

    private List<TipoEntity> findTipoEntityEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(TipoEntity.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public TipoEntity findTipoEntity(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(TipoEntity.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getTipoEntityCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<TipoEntity> rt = cq.from(TipoEntity.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }
    
}
